package cn.edu.zafu.bigdata.cccnnn.workfour;

import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class TestToFile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要写入文件的文本：");
        String content = scanner.nextLine();
        System.out.println("请输入文件名（不需要输入路径，只需文件名和扩展名）：");
        String studentId = scanner.nextLine();

        // 构建完整的文件路径
        String baseDir = "C:\\Users\\zjqzs\\IdeaProjects\\LearnJava\\src\\main\\java\\cn\\edu\\zafu\\bigdata\\cccnnn\\workfour";
        String fileName = baseDir + "\\" + studentId;

        // 将用户输入的文本写入到指定的文件中
        writeToFile(fileName, content);

        // 读取文件内容并将其打印到控制台
        System.out.println("文件内容如下：");
        readFromFile(fileName);

        scanner.close();
    }

    public static void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write(content);
            System.out.println("文本已写入文件：" + fileName);
        } catch (IOException e) {
            System.err.println("写入文件时发生错误：" + e.getMessage());
        }
    }

    public static void readFromFile(String fileName) {
        try (FileReader reader = new FileReader(fileName)) {
            int i;
            while ((i = reader.read()) != -1) {
                System.out.print((char) i);
            }
        } catch (IOException e) {
            System.err.println("读取文件时发生错误：" + e.getMessage());
        }
    }
}